//
//  Tab1ViewController.m
//  Test
//
//  Created by 祝文博 on 15/3/3.
//  Copyright (c) 2015年 KevinLab. All rights reserved.
//

#import "Tab1ViewController.h"
#import "DianpingStore.h"
#import "MyCell.h"
#import "DetailViewController.h"
#import "API.h"
#import "Banner.h"
#import "BannerCell.h"
#import "SmallBannerCell.h"
#import "BannerDetailViewController.h"

NS_ENUM(NSInteger, TABLE_VIEW_SECTION) {
    TABLE_VIEW_SECTION_BANNER,
    TABLE_VIEW_SECTION_SMALL_BANNER,
    TABLE_VIEW_SECTION_DIANPING_ITEM,
    TABLE_VIEW_SECTION_COUNT
};

@interface Tab1ViewController ()

@property (nonatomic, strong) NSMutableArray *banners;
@property (nonatomic, strong) NSMutableArray *smallBanners;

@end

@implementation Tab1ViewController

- (void)viewDidLoad {
    self.items = [[NSMutableArray alloc] init];
    [super viewDidLoad];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   @"杭州",@"city",
                                   @"30.2667370000",@"latitude",
                                   @"120.0982200000",@"longitude",
                                   @"美食",@"category",
                                   nil];
    
    [DianpingStore getStoreListWithParams:params resultBlock:^(NSArray *storeList, NSError *error){
        self.items = [NSMutableArray arrayWithArray:storeList];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }];
    //addObserver观察者
    //selector 收到通知后调用的方法
    //name通知的名字，也是通知的唯一标示，编译器就通过这个找到通知的
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bannerPressedNotification:) name:BannerSlidingViewDidPressNotificationName object:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    CGRect rect = self.tableView.frame;
    rect.size.height -= 49;
    self.tableView.frame = rect;
    
    NSArray *dictBanners = @[@{
                                 @"imageURL":@"http://img.tqmall.com/config/2014/10/22/141396422688_web.jpg",
                                 @"targetURL":@"http://app.360cec.com/activity/tuesday/p-11/yure/index.html?spm=0&type=1&scale=2&cityId=383"
                                 },
                             @{
                                 @"imageURL":@"http://img.tqmall.com/config/2014/09/29/1411984334_web.jpg",
                                 @"targetURL":@"http://app.360cec.com/activity/tuesday/p-11/yure/index.html?spm=0&type=1&scale=2&cityId=383"
                                 },
                             @{
                                 @"imageURL":@"http://img.tqmall.com/config/2014/09/30/1412069225_web.jpg",
                                 @"targetURL":@"http://112.124.66.38:9100/activity/pm-8/index_0209.html?actId=269&type=1&scale=2&cityId=383"
                                 },
                             @{
                                 @"imageURL":@"http://img.tqmall.com/config/2015/01/13/142112254861_web.jpg",
                                 @"targetURL":@"http://112.124.66.38:8080/activity/yuanxiao/index.html?actId=270&type=1&scale=2&cityId=383"
                                 }];
    self.banners = [NSMutableArray array];
    for (int i = 0; i < dictBanners.count; i++) {
        Banner *banner = [[Banner alloc] initWithAttributes:dictBanners[i]];
        [self.banners addObject:banner];
    }
    
    NSArray *dictSmallBanners = @[@{
                              @"title":@"机油混批",
                              @"subTitle":@"机油混批大放送",
                              @"imageURL":@"http://img.tqmall.com/config/2014/12/22/141922784000_web.png",
                              @"targetURL":@"http://www.baidu.com/"
                              },
                          @{
                              @"title":@"电瓶混批",
                              @"subTitle":@"特惠风暴不买后悔",
                              @"imageURL":@"http://img.tqmall.com/config/2014/12/22/141922784000_web.png",
                              @"targetURL":@"http://www.baidu.com/"
                              },
                          @{
                              @"title":@"搭配组合",
                              @"subTitle":@"机油套餐直击底价",
                              @"imageURL":@"http://img.tqmall.com/config/2014/08/20/1408512142_web.png",
                              @"targetURL":@"http://www.baidu.com/"
                              },
                          @{
                              @"title":@"品牌专场",
                              @"subTitle":@"电瓶平价特卖惠",
                              @"imageURL":@"http://img.tqmall.com/config/2014/11/12/141580645329_web.png",
                              @"targetURL":@"http://www.baidu.com/"
                              }];
    self.smallBanners = [NSMutableArray array];
    for (int i = 0; i < dictSmallBanners.count; i++) {
        Banner *banner = [[Banner alloc] initWithAttributes:dictSmallBanners[i]];
        [self.smallBanners addObject:banner];
    }
    
}

#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    switch (indexPath.section) {
        case TABLE_VIEW_SECTION_BANNER : {
            NSString *cellTableIdentifier = @"bannerCell";
            
            BannerCell *bannerCell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellTableIdentifier];
            if (bannerCell == nil) {
                bannerCell = [[BannerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellTableIdentifier];
            }
            
            bannerCell.banners = self.banners;
            
            cell = bannerCell;
            
            break;
        }
        case TABLE_VIEW_SECTION_SMALL_BANNER : {
            NSString *cellTableIdentifier = @"smallBannerCell";
            
            SmallBannerCell *smallBannerCell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellTableIdentifier];
            if (smallBannerCell == nil) {
                smallBannerCell = [[SmallBannerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellTableIdentifier];
            }
            
            NSUInteger index = indexPath.row * [SmallBannerCell numberOfItems];
            @try {
                smallBannerCell.banner1 = self.smallBanners[index];
                smallBannerCell.subItem1.tag = index;
                [smallBannerCell.subItem1 removeTarget:self action:@selector(smallBannerPressed:) forControlEvents:UIControlEventTouchUpInside];
                [smallBannerCell.subItem1 addTarget:self action:@selector(smallBannerPressed:) forControlEvents:UIControlEventTouchUpInside];
            } @catch (NSException *exception) {
                smallBannerCell.banner1 = nil;
            }
            
            @try {
                smallBannerCell.banner2 = self.smallBanners[index + 1];
                smallBannerCell.subItem2.tag = index + 1;
                [smallBannerCell.subItem2 removeTarget:self action:@selector(smallBannerPressed:) forControlEvents:UIControlEventTouchUpInside];
                [smallBannerCell.subItem2 addTarget:self action:@selector(smallBannerPressed:) forControlEvents:UIControlEventTouchUpInside];
            } @catch (NSException *exception) {
                smallBannerCell.banner2 = nil;
                
            }
            
            cell = smallBannerCell;
            
            break;
        }
        case TABLE_VIEW_SECTION_DIANPING_ITEM : {
            NSString *cellTableIdentifier = @"cellTableIdentifier";
            MyCell *myCell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellTableIdentifier];
            if (myCell == nil) {
                myCell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellTableIdentifier];
            }
            
            DianpingStore *dianpingStore = self.items[indexPath.row];
            
            myCell.name = dianpingStore.name;
            myCell.address = dianpingStore.address;
            myCell.imageUrl = dianpingStore.sPhotoUrl;
            cell = myCell;
            break;
        }
        default:
            break;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 80.0;
    
    switch (indexPath.section) {
        case TABLE_VIEW_SECTION_BANNER:
            height = 0.0;
            for (Banner *banner in self.banners) {
                if (banner.image) {
                    height = [BannerCell cellHeightWithBanner:banner];
                    break;
                }
            }
            break;
        case TABLE_VIEW_SECTION_SMALL_BANNER:
            height = self.smallBanners.count > 0 ? [SmallBannerCell cellHeight] : 0.0;
            break;
        case TABLE_VIEW_SECTION_DIANPING_ITEM:
            height = 80.0;
        default:
            break;
    }
    return height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger number = 1;
    
    switch (section) {
        case TABLE_VIEW_SECTION_BANNER:
            number = self.banners.count > 0 ? 1 : 0;
            break;
        case TABLE_VIEW_SECTION_SMALL_BANNER:
            number = (self.smallBanners.count + 1) / [SmallBannerCell numberOfItems];
            break;
        case TABLE_VIEW_SECTION_DIANPING_ITEM:
            number = self.items.count;
            break;
        default:
            break;
    }
    return number;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return TABLE_VIEW_SECTION_COUNT;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailViewController = [[DetailViewController alloc] init];
    DianpingStore *dianpingStore = self.items[indexPath.row];
    detailViewController.title = dianpingStore.name;
    detailViewController.item = dianpingStore;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (void)bannerPressedNotification:(NSNotification *)notification
{
    Banner *banner = notification.object;
    if (banner.targetURL.length == 0) {
        return;
    }
    BannerDetailViewController *bannerDetailViewController = [[BannerDetailViewController alloc] init];
    bannerDetailViewController.banner = banner;
    [self.navigationController pushViewController:bannerDetailViewController animated:YES];
}

- (IBAction)smallBannerPressed:(SmallBannerSubItem *)sender
{
    Banner *banner = self.smallBanners[sender.tag];
    
    BannerDetailViewController *bannerDetailViewController = [[BannerDetailViewController alloc] init];
    bannerDetailViewController.banner = banner;
    [self.navigationController pushViewController:bannerDetailViewController animated:YES];
}

@end
